from fastapi import APIRouter, Depends
from schema.resp import RestfulModel
from dependencies import get_mongo_db_of_condition_safety
from typing import List
from pymongo.database import Database
import utils
from random import randint
import hashlib
from datetime import datetime, timedelta, date
import re

condition_safety_abnormal_statistic_router = APIRouter(prefix='/condition_safety/abnormal_statistic', tags=['车辆状态安全-异常车辆统计'])


class MongoCollectionName:
    """
    mongo 中 collection 的 name 常量
    """
    STATUS_STSTISTICS='Abnormal_state_count'
    STATUS_DATA_RAW = 'Abnormal_state_raw'


#获取不同异常类型的次数统计数据 /vehicle_status/abnormal_static/bar
#field1 异常1
#field2 异常2
#field3 异常3
@condition_safety_abnormal_statistic_router.get('/count',summary='不同异常类型的次数统计')
async def get_abnormal_count(mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    abnormal_count_col = mongo_db[MongoCollectionName.STATUS_STSTISTICS]

    ab_current_cursor = abnormal_count_col.find_one({"name": re.compile("总电流异常")})
    ab_current_num = ab_current_cursor['count']

    ab_accelerator_pedal_cursor = abnormal_count_col.find_one({"name": re.compile("加速踏板异常")})
    ab_accelerator_pedal_num = ab_accelerator_pedal_cursor['count']

    ab_brake_pedal_cursor = abnormal_count_col.find_one({"name": re.compile("制动踏板异常")})
    ab_brake_pedal_num = ab_brake_pedal_cursor['count']

    ab_soc_cursor = abnormal_count_col.find_one({"name": re.compile("SOC异常")})
    ab_soc_num = ab_soc_cursor['count']

    ab_power_consumption_cursor = abnormal_count_col.find_one({"name": re.compile("耗电异常")})
    ab_power_consumption_num = ab_power_consumption_cursor['count']

    result = {
        '总电流异常': ab_current_num,
        '加速踏板异常': ab_accelerator_pedal_num,
        '制动踏板异常': ab_brake_pedal_num,
        'SOC异常': ab_soc_num,
        '耗电异常': ab_power_consumption_num
    }
    return RestfulModel.success(result)


def week_day_get(d):
    for i in range(0,8):
        oneday = timedelta(days=i)
        day = d - oneday
        date_to = datetime(day.year, day.month, day.day)
        yield str(date_to)[:]


def display(day_list, res):
    flag = 0
    count_result = []
    for type in [
            "总电流异常",
			"加速踏板异常",
			"制动踏板异常",
			"SOC异常",
			"耗电异常"]:
        for time in day_list:
            for i in res:
                if i['type'] == type and i['time'].date() == datetime.strptime(time, '%Y-%m-%d %H:%M:%S').date():
                    count_result.append(i)
                    flag = 1
                    break
            if flag == 1:
                flag = 0
                continue
            else:
                data = {
                    'type': type,
                    'time': datetime.strptime(time, '%Y-%m-%d %H:%M:%S'),
                    'count': 0
                }
                count_result.append(data)

    n=len(day_list)

    ab_current=[0]*n
    ab_accelerator_pedal=[0]*n
    ab_brake_pedal=[0]*n
    ab_soc=[0]*n
    ab_power_consumption=[0]*n

    for data in count_result:
        time=str(data['time']).split(' ')[0]+' '+'00:00:00'
        if data['type']=='总电流异常':
            ab_current[day_list.index(time)]=data['count']
        elif data['type']=='加速踏板异常':
            ab_accelerator_pedal[day_list.index(time)]=data['count']
        elif data['type']=='制动踏板异常':
            ab_brake_pedal[day_list.index(time)]=data['count']
        elif data['type']=='SOC异常':
            ab_soc[day_list.index(time)]=data['count']
        elif data['type'] == '耗电异常':
            ab_power_consumption[day_list.index(time)] = data['count']

    result={
        'x':day_list,
        'y':{
            '总电流异常':ab_current,
            '加速踏板异常':ab_accelerator_pedal,
            '制动踏板异常':ab_brake_pedal,
            'SOC异常':ab_soc,
            '耗电异常': ab_power_consumption
        }
    }
    return result


#获取不同异常类型的次数统计柱状图数据 /vehicle_status/abnormal_static/histogram
#x array[string] 时间列表
#y 攻击次数 field5 异常1攻击次数列表 field6 异常2攻击次数列表

@condition_safety_abnormal_statistic_router.get('/histogram',summary='不同异常类型的次数统计柱状图')
async def get_abnormal_histogram(mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    status_data = []
    status_data_col = mongo_db[MongoCollectionName.STATUS_DATA_RAW]
    for x in status_data_col.find():
        status_data.append(x)

    res = []
    flag = 0
    for res_data in status_data:
        for i in res:
            if res_data['报文时间'].date() == i['time'].date() and res_data['type'] == i['type']:
                i['count'] += 1
                flag = 1
                break
        if flag == 1:
            flag = 0
            continue
        else:
            data_new = {
                'type': res_data['type'],
                'time': res_data['报文时间'],
                'count': 1
            }
            res.append(data_new)

    d = datetime.now()

    week_days = week_day_get(d)
    week_list = []
    for obj in week_days:
        week_list.append(obj)
    list_week_day = week_list[::-1]

    display_result = display(list_week_day, res)

    return RestfulModel.success(display_result)

#获取异常车辆日志 /vehicle_status/abnormal_static/list
#请求参数：keywords page size
#total_page 总页数
#total_count 总记录数
#docs
@condition_safety_abnormal_statistic_router.get('/list',summary='异常车辆日志')
async def get_abnormal_car_list(page=1,size=8,vin='',type='',mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    status_data_col = mongo_db[MongoCollectionName.STATUS_DATA_RAW]
    if vin=='':
        cursor = status_data_col.aggregate([
                            {'$project': {'_id': 0}},
                            {'$sample': {'size': 2000}}
                ])
        data = []
        for u in cursor:
            if type=='':
                data.append(u)
            else:
                if u['type'] == type:
                    data.append(u)
    else:
        cursor = status_data_col.find({'VIN':re.compile(vin)}, {'_id': 0})
        data = []
        for u in cursor:
            if type == '':
                data.append(u)
            else:
                if u['type'] == type:
                    data.append(u)

    total_count = len(data)
    total_page = int((total_count + int(size) - 1) / int(size))
    docs = data[(int(page) - 1) * int(size):int(page) * int(size)]
    result = {
        'total_page': total_page,
        'total_count': total_count,
        'docs': docs
    }
    return RestfulModel.success(result)


#获取异常排名 /vehicle_status/abnormal_static/sort
#field1 异常1的次数
#field2 异常2的次数
#field3 异常3的次数
@condition_safety_abnormal_statistic_router.get('/sort',summary='异常排名')
async def get_abnormal_sort(mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    abnormal_count_col = mongo_db[MongoCollectionName.STATUS_STSTISTICS]

    ab_current_cursor = abnormal_count_col.find_one({"name": re.compile("总电流异常")})
    ab_current_num = ab_current_cursor['count']

    ab_accelerator_pedal_cursor = abnormal_count_col.find_one({"name": re.compile("加速踏板异常")})
    ab_accelerator_pedal_num = ab_accelerator_pedal_cursor['count']

    ab_brake_pedal_cursor = abnormal_count_col.find_one({"name": re.compile("制动踏板异常")})
    ab_brake_pedal_num = ab_brake_pedal_cursor['count']

    ab_soc_cursor = abnormal_count_col.find_one({"name": re.compile("SOC异常")})
    ab_soc_num = ab_soc_cursor['count']

    ab_power_consumption_cursor = abnormal_count_col.find_one({"name": re.compile("耗电异常")})
    ab_power_consumption_num = ab_power_consumption_cursor['count']

    result = {
        '总电流异常': ab_current_num,
        '加速踏板异常': ab_accelerator_pedal_num,
        '制动踏板异常': ab_brake_pedal_num,
        'SOC异常': ab_soc_num,
        '耗电异常': ab_power_consumption_num
    }

    result_order = sorted(result.items(), key=lambda x: x[1], reverse=True)
    result_order_dict = dict(result_order)

    return RestfulModel.success(result_order_dict)

